package server;

import server.classloader.WebappClassLoader;
import server.mapping.Context;
import server.mapping.Service;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Iterator;
import java.util.Map;

public class RequestProcessorV1 extends Thread {

    private Socket socket;
    private Service service;

    public RequestProcessorV1(Socket socket, Service service) {
        this.socket = socket;
        this.service = service;
    }

    @Override
    public void run() {
        Request request = null;
        Response response = null;
        try{
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            request = new Request(inputStream);
            response = new Response(socket.getOutputStream());

            // 域名
            String hostname = request.getHostname();
            // 全路径
            String path = request.getUrl();

            // 静态资源处理
            Map<String, Context> contextMap = service.getHostMap().get(hostname).getContextMap();
            Context context = null;

            // 上下文路径 /demo1
            String context_path = null;
            Iterator<Map.Entry<String, Context>> iterator = contextMap.entrySet().iterator();
            while (iterator.hasNext()){
                Map.Entry<String, Context>  entry = iterator.next();
                String key = entry.getKey();
                if (path.indexOf(key) == 0){
                    context = entry.getValue();
                    context_path = key;
                    break;
                }
            }

            if (null == context_path){
                response.output404();
            }else {
                String uri = path.split(context_path)[1];
                HttpServlet httpServlet = context.getServletMap().get(uri);
                WebappClassLoader classLoader = context.getWebappClassLoader();
                if (null == httpServlet) {
                    response.outputHtmlV1(uri, classLoader.getRootDir());
                } else {
                    httpServlet.service(request, response);
                }
            }

            socket.close();

        }catch (Exception e) {
            try {
                response.output404();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }

    }
}
